package com.os.ui;

import com.os.pojo.vo.PcbInfoVo;
import com.os.pojo.vo.SegmentVo;
import com.os.service.OsService;
import com.os.service.impl.OsServiceImpl;
import com.os.utils.ScreenUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.List;

public class MainWindow {
    /*
     * 主界面
     */
    final int WIDTH = 1200;
    final int HEIGHT = 800;

    static String[][] data;
    static String[] column = {"序号", "进程名","进程大小", "进程段总数"};
    static DefaultTableModel model;

    static OsService osService;

    static Integer memorySize = 32;

    static Integer pageSize = 4;

    // 表格
    static ElementUITable jt;

    public void init(JFrame jf) {
        osService = new OsServiceImpl();
//        osService.open("C:\\Users\\the_shun\\Desktop\\segData\\1.txt");
        // 组装视图
        // 设置窗口相关属性
        // 设置窗口图标
        jf.setBounds((ScreenUtils.getScreenWidth() - WIDTH) / 2, (ScreenUtils.getScreenHeight() - HEIGHT) / 2, WIDTH, HEIGHT);
        jf.setResizable(false);

        JPanel topPanel = initTopBox(jf);
        JPanel bottomPanel = initBottomBox();

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // 设置为垂直布局
        panel.add(topPanel);
        panel.add(bottomPanel);

        jf.add(panel);
        // 设置可视
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);
    }

    public static JPanel initTopBox(JFrame jf) {
        // 设置窗口的内容
        JPanel topPanel = new JPanel();
        // 布置上部盒子
        Box topBox = Box.createHorizontalBox();
        Box innerBox = Box.createHorizontalBox();
        // 创建一个空白边框
        TitledBorder titledBorder = new TitledBorder(new LineBorder(Color.GRAY, 1), "内存预设",
                TitledBorder.LEFT, TitledBorder.TOP, new Font("宋体", Font.PLAIN, 13), Color.BLACK);
        topBox.setBorder(titledBorder);
        // 让innerBox离topBox远一点
        innerBox.setBorder(new EmptyBorder(10, 10, 10, 10));
        JLabel jLabel = new JLabel("请输入内存大小(单位为一个字符)：");
        // 创建一个下拉框
        Integer[] options = {16, 32, 64};
        JComboBox<Integer> comboBox = new JComboBox<>(options);

        JLabel jLabel2 = new JLabel("请输入页面大小(单位为一个字符)：");
        // 创建一个下拉框
        Integer[] options2 = {2, 4, 8, 16};
        JComboBox<Integer> comboBox2 = new JComboBox<>(options2);
        comboBox.setSelectedItem(32);
        comboBox2.setSelectedItem(4);
        JButton jButton = new JButton("查看内存详情");
        JButton jButton2 = new JButton("打开文件");
        JButton jButton3 = new JButton("重置设置");

        // 进入内存管理
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 如果当前内存没有进程
                if (osService.getPcbInfoList().size() <= 0) {
                    //弹出警告框
                    JOptionPane.showMessageDialog(jf, "当前内存没有进程，请打开文件载入虚拟内存！", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                ;
//                jf.dispose(); // 关闭当前窗口
                MemoryProcessWindow.setUIFont(new javax.swing.plaf.FontUIResource("宋体", Font.PLAIN, 15));

                // 跳转到内存进程管理界面
                SwingUtilities.invokeLater(() -> {
                    MemoryProcessWindow memoryProcessWindow = new MemoryProcessWindow();
                    memoryProcessWindow.init(osService,memorySize, pageSize);
                });
            }
        });


        // 打开文件载入虚拟内存
        jButton2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 打开文件
                JFileChooser fileChooser = new JFileChooser();
                int returnValue = fileChooser.showOpenDialog(null);

                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    // 在此处执行打开文件的相关操作
                    // 例如：Desktop.getDesktop().open(selectedFile);
                    osService.open(selectedFile.getAbsolutePath());
                    List<PcbInfoVo> pcbInfoList = osService.getPcbInfoList();
                    System.out.println(osService.getPcbInfoList());
                    data = new String[pcbInfoList.size()][4];
                    for (int j = 0; j < pcbInfoList.size(); j++) {
                        PcbInfoVo pcbInfoVo = pcbInfoList.get(j);
                        List<SegmentVo> sementInfoByPcbId = osService.getSegmentInfoByPcbId(pcbInfoVo.getId());
                        String numCount = "";
                        for (int i = 0; i < sementInfoByPcbId.size(); i++) {
                            if (i != 0) {
                                numCount += ",";
                            }
                            numCount += sementInfoByPcbId.get(i).getLen();
                        }
                        String[] pcbInfo = {pcbInfoVo.getId() + "" ,pcbInfoVo.getName(), pcbInfoVo.getLen() +"", sementInfoByPcbId.size() + ""};
                        data[j] = pcbInfo;
                    }
                    for (int i = 0; i < data.length; i++) {
                        System.out.println(data[i][0] + data[i][1] + data[i][2] + data[i][3]);
                    }
                    model.setDataVector(data, column);
                    model.fireTableDataChanged();
                    System.out.println(selectedFile.getAbsolutePath());
                }
            }
        });

        jButton3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                memorySize = (int) comboBox.getSelectedItem();
                pageSize = (int) comboBox2.getSelectedItem();
                if (memorySize == null || pageSize == null) {
                    //弹出警告框
                    JOptionPane.showMessageDialog(jf, "内存大小或页面大小不能为空！", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                // 重置设置
                osService.changeMemoryInfo(memorySize, pageSize);
                // 重置表格
                data = new String[0][4];
                model.setDataVector(data, column);
                model.fireTableDataChanged();
                // 获取特定列索引的表格列
                TableColumn columnIndex = jt.getColumnModel().getColumn(3); // 假设“进程段各大小(以逗号分割)”列的索引为3
                // 设置列的首选宽度
                columnIndex.setPreferredWidth(300); // 将首选宽度设置为您希望的值（以像素为单位）
            }
        });

        // 第一行
        Box row1Box = Box.createHorizontalBox();
        row1Box.add(jLabel);
        row1Box.add(comboBox);
//        row1Box.add(jTextField);
        // 第二行
        Box row2Box = Box.createHorizontalBox();
        row2Box.add(jLabel2);
        row2Box.add(comboBox2);
        // 将两行组合到一起
        Box leftBox = Box.createVerticalBox();
        Component row1Row2Strut = Box.createVerticalStrut(10); // 添加20像素的水平间距
        leftBox.add(row1Box);
        leftBox.add(row1Row2Strut);
        leftBox.add(row2Box);
        // 创建一个垂直Box和一个水平Box组合成整体布局
        Box containerBox = Box.createHorizontalBox();

        containerBox.add(leftBox);
        containerBox.add(Box.createHorizontalStrut(600)); // 让按钮靠右
        containerBox.add(jButton3);
        containerBox.add(Box.createHorizontalStrut(20));
        containerBox.add(jButton2);
        containerBox.add(Box.createHorizontalStrut(20));
        containerBox.add(jButton);


        innerBox.add(leftBox);
        innerBox.add(containerBox);
        topBox.add(innerBox);
        topPanel.add(topBox);
        return topPanel;
    }

    public static JPanel initBottomBox() {
        JPanel jPanel = new JPanel();
        // 布置下部的盒子
        Box bottomBox = Box.createHorizontalBox();
        Box innerBox = Box.createHorizontalBox();
        TitledBorder titledBorder2 = new TitledBorder(new LineBorder(Color.GRAY, 1), "进程预设",
                TitledBorder.LEFT, TitledBorder.TOP, new Font("宋体", Font.PLAIN, 13), Color.BLACK);
        bottomBox.setBorder(titledBorder2);
        innerBox.setBorder(new EmptyBorder(10, 10, 10, 10));

        model = new DefaultTableModel(data, column);
        jt = new ElementUITable(model);
        // 获取特定列索引的表格列
        TableColumn columnIndex = jt.getColumnModel().getColumn(3); // 假设“进程段各大小(以逗号分割)”列的索引为3
        // 设置列的首选宽度
        columnIndex.setPreferredWidth(300); // 将首选宽度设置为您希望的值（以像素为单位）
        JScrollPane scrollPane = new JScrollPane(jt);
        jt.setPreferredScrollableViewportSize(new Dimension(1140, 570));
        innerBox.add(scrollPane);
        bottomBox.add(innerBox);
        jPanel.add(bottomBox);
        return jPanel;
    }

    public static void main(String[] args) {
        JFrame jf = new JFrame("段页式虚拟存储系统");
        Image icon = Toolkit.getDefaultToolkit().getImage("src/main/resources/任务进程.png");
        jf.setIconImage(icon);
        new MainWindow().init(jf);
    }
}
